import { userApi } from '../../services/api';

Page({
  data: {
    userInfo: null,
    hasUserInfo: false,
    boxAnimation: null
  },

  onLoad() {
    this.initAnimation();
    this.checkUserAuth();
  },

  initAnimation() {
    const animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    });
    
    this.setData({
      boxAnimation: animation
    });
    
    this.startBoxAnimation();
  },

  startBoxAnimation() {
    this.data.boxAnimation.translateY(-20).step()
      .translateY(0).step();
    
    this.setData({
      animationData: this.data.boxAnimation.export()
    });

    setTimeout(() => {
      this.startBoxAnimation();
    }, 3000);
  },

  // 修改手机号授权登录逻辑
  async handleGetPhoneNumber(e) {
    // 打印手机号授权结果
    console.log('手机号授权结果：', {
      errMsg: e.detail.errMsg,
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv
    });

    if (e.detail.errMsg !== "getPhoneNumber:ok") {
      wx.showToast({
        title: '请允许获取手机号',
        icon: 'none'
      });
      return;
    }

    try {
      wx.showLoading({
        title: '登录中...',
        mask: true
      });

      // 获取微信用户信息
      const userProfile = await wx.getUserInfo({
        withCredentials: true,
        lang: 'zh_CN'
      });
      console.log('获取到的微信用户信息：', userProfile);

      const { code } = await wx.login();
      console.log('获取到的登录code：', code);
      
      // 构建登录参数
      const loginParams = {
        code,
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        userInfo: {
          nickName: userProfile.userInfo.nickName,
          gender: userProfile.userInfo.gender,
          avatarUrl: userProfile.userInfo.avatarUrl,
          country: userProfile.userInfo.country,
          province: userProfile.userInfo.province,
          city: userProfile.userInfo.city,
          language: userProfile.userInfo.language
        }
      };
      console.log('发送登录请求参数：', loginParams);

      const loginResult = await userApi.login(loginParams);
      console.log('登录接口返回结果：', loginResult);

      // 保存登录信息
      wx.setStorageSync('token', loginResult.token);
      wx.setStorageSync('userInfo', {
        ...loginResult.userInfo,
        nickName: userProfile.userInfo.nickName,
        gender: userProfile.userInfo.gender,
        avatarUrl: userProfile.userInfo.avatarUrl
      });

      this.setData({
        userInfo: loginResult.userInfo,
        hasUserInfo: true
      });

      wx.hideLoading();
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      });

    } catch (err) {
      console.error('登录失败，错误详情：', err);
      wx.hideLoading();
      wx.showToast({
        title: err.message || '登录失败，请重试',
        icon: 'none'
      });
    }
  },

  checkUserAuth() {
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    if (token && userInfo) {
      this.setData({
        userInfo,
        hasUserInfo: true
      });
    }
  },

  handleBoxTap(e) {
    const { type } = e.currentTarget.dataset;
    
    if (!this.data.hasUserInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    if (type === 'same') {
      wx.navigateTo({
        url: '/pages/profile/profile'
      });
    } else {
      wx.navigateTo({
        url: '/pages/draw/draw'
      });
    }
  }
}); 